from alipay import AliPay
from django import http
from django.conf import settings
from django.shortcuts import render

# Create your views here.
from django.views import View

from meiduo_mall.utils.my_loginview import LoginRequiredView
from meiduo_mall.utils.response_code import RET
from orders.models import OrderInfo
from pays.models import PayModel


class AliPaymentView(LoginRequiredView):

    def get(self, request, order_id):

        app_private_key_string = """-----BEGIN RSA PRIVATE KEY-----
        MIIEpgIBAAKCAQEA2X5A6fWSpJ5Dc84EKFOVF9r5QMJktPF9ghCMHzztaEaPq9cWGLVUV1GGuNpTy1/1AEpMAEMeDXmMRPLpBoXEJh4KtjJqF4W8aeyy6UwlR+qBVtaJ7IOIZ6CFcSBgt3hzn006YuEpylDC1R/7hsGlROAK7bAiAiaWW2w1qGzFqZOIScylfyJTi69GbWHyfTRjxNtO818T0kRBiPRvCMrJqLueNo58K8YGMjZa4ZrntQ17SiIj6IVCil0wyDXLR02wBllWO37LKfgjQG86IRLvzH5nTu3Vv04/49ZZPfDB5AAShmkDFIw0SZlywxAZvcWyCG3rOYkTBloXBiBXFIj0swIDAQABAoIBAQCZhsvf2x/W4HkQ6B57MPUPz90e35ojOEy2YWPoMSQM9bI5RS0t5+JPeRc2qbd42pWhzNB1Zutx65kemrHvjsF1fsNk9ZV6YUctJo7srHmsmFcQq4TU1cyWCfPodUiQepBzpRpP7k2HqRa/R0JQT6WQRu6v9iMrjX2Zr3r5Fz84gcURifYTxBQZ9Mx0W6uGD+r/E+lQDbybmrtug90CWzHir+aChtxafAkD5d1J69ScFqbJCeHFGpSIsqmgVyh/VezaqGYAX+JG9y10xhXchA5IaDqXeeDNcZi46yBM7v4QpDGUNvh1VcrhRTPHFGQ5sqmSP3Jq0zC3JZZ8h48JU3NRAoGBAO1d4SX02iknaX6A4Iutjosv4CVlK0Fp+O3ZQh90P3hc1hBS50ghXyr7Bn6TGcUM77GD0DhTzYJ1QVm2yoa+sXmR92A2drCAi0rBuHas3ybX8OxDyxDWHNrPmjdVG6ruhpPtD5JD8AnLsrkdaXvNSJ1rbVYuw6Pi4kDZUUQ79knnAoGBAOqQ/ttyAp5pOc3C0zC56iBCjqIc43rhBWW4Ij/JLfwfVy02ktWbLBotqgQVhfU0Dn/QHzz3EmIc+JaxytdUMVKeMDhxIKi6tFPiu4evx08ZxP07HxfgOeTIbI6AowER0Rd+LQYDRnKiYQOeuMKgmWUczY7MbkUUoANoJur/mt1VAoGBAJe+4ZXrX6DZolaOO37wOGWA+NHPSITsI4ii0OPc5EqlRvBun478TqPikPdQQTQ5He8lLnMkGAijv2CEPBtCQ6FNkJEAoIYb13C2QaAUyiBCArJ4cJRV3WKBP7zJ+wMetAhTkBXYutb4U0yGog3UYezJZb+n68iU3kHI7GwrzTrXAoGBAK1kQ1B6JZ9tz1Hfi3fAZmY0bPU+/5Ts062OgJrAHyL5E9sTNVV7IA215bChLGXGdlVaxkytosQuAEB86qFj1hXpY2HFlkvDv9smhlNVx7IcLXa3hlOC56jL0xs/0b7Pqc2A8s04DJJen/IqGQ+d4eZRdU3ypiygg2whSGt8SMEFAoGBAIcAgfg4qD5RMbjUfFkB2FSpck7Dsk1V5m6ry581Rntj3BXi1V2qjN9ZRR0GopdBet4BQTsx9fPsCnmgG4AXwXf1LhifrxE8l6W5mJiqqp2nikTBMDcNTR3Kd/0PxocZYVQhXkWiamqkRryzAIGbpFb7I8uyBeRc3ifqJi9QS61b
        -----END RSA PRIVATE KEY-----
        """

        alipay_public_key_string = """-----BEGIN PUBLIC KEY-----
        MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAyl1XzawrgqvhUxswJBBLL/7Y0YmYZDmv8eQMbcKJsi2xeLauNKfGnQJYgcNe0pFESaQrFsIeHUsD7zUd0Tz41ue2eX9/j5GqS4rySM2YRnEVga9+2bBLl4rJuRIiEys4VUxbug87W9CwTzKGO3fdTWIySjVHmCKuAAMJ6EGX9sXT+8sgFiCbMZ6JHFj9CRU8HuneUNcP6HTe3oItT6EWOfVp3ElbxsaMRB5LWkXpb0PkpvkAkr0lYHAa9bWsh7h0w0NwZuyJ8VyUQR6j5yML+EnvmUeNSZpzAV0WUdoo2r6tQ9E43C3Xfto+8e0t/0hq90SyFf9Y1rMLjTelN/vUZwIDAQAB
        -----END PUBLIC KEY-----
        """

        alipay = AliPay(
            appid=settings.APPID,
            app_notify_url=None,
            app_private_key_string=app_private_key_string,
            alipay_public_key_string=alipay_public_key_string,
            sign_type=settings.SIGN_TYPE,
            debug=settings.DEBUG
        )

        gateway = settings.GATEWAY

        subject = '美多商城订单'
        alipay_url = 'https://openapi.alipaydev.com/gateway.do?'

        try:
            order = OrderInfo.objects.get(order_id=order_id)
        except Exception as e:
            return http.HttpResponseForbidden('订单不存在')

        order_string = alipay.api_alipay_trade_page_pay(
            out_trade_no=order_id,
            total_amount=str(order.total_amount),
            subject=subject,
            return_url=settings.RETURN_URL,
            # notify_url='https://www.luffycity.com/free-course'
        )
        #
        alipay_url = alipay_url + order_string
        print(alipay_url)
        return http.JsonResponse({'code': RET.OK, 'alipay_url': alipay_url})


class AliOrderChangeView(LoginRequiredView):

    def get(self, request):
        app_private_key_string = """-----BEGIN RSA PRIVATE KEY-----
        MIIEpgIBAAKCAQEA2X5A6fWSpJ5Dc84EKFOVF9r5QMJktPF9ghCMHzztaEaPq9cWGLVUV1GGuNpTy1/1AEpMAEMeDXmMRPLpBoXEJh4KtjJqF4W8aeyy6UwlR+qBVtaJ7IOIZ6CFcSBgt3hzn006YuEpylDC1R/7hsGlROAK7bAiAiaWW2w1qGzFqZOIScylfyJTi69GbWHyfTRjxNtO818T0kRBiPRvCMrJqLueNo58K8YGMjZa4ZrntQ17SiIj6IVCil0wyDXLR02wBllWO37LKfgjQG86IRLvzH5nTu3Vv04/49ZZPfDB5AAShmkDFIw0SZlywxAZvcWyCG3rOYkTBloXBiBXFIj0swIDAQABAoIBAQCZhsvf2x/W4HkQ6B57MPUPz90e35ojOEy2YWPoMSQM9bI5RS0t5+JPeRc2qbd42pWhzNB1Zutx65kemrHvjsF1fsNk9ZV6YUctJo7srHmsmFc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VQhXkWiamqkRryzAIGbpFb7I8uyBeRc3ifqJi9QS61b
        -----END RSA PRIVATE KEY-----
        """

        alipay_public_key_string = """-----BEGIN PUBLIC KEY-----
        MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAyl1XzawrgqvhUxswJBBLL/7Y0YmYZDmv8eQMbcKJsi2xeLauNKfGnQJYgcNe0pFESaQrFsIeHUsD7zUd0Tz41ue2eX9/j5GqS4rySM2YRnEVga9+2bBLl4rJuRIiEys4VUxbug87W9CwTzKGO3fdTWIySjVHmCKuAAMJ6EGX9sXT+8sgFiCbMZ6JHFj9CRU8HuneUNcP6HTe3oItT6EWOfVp3ElbxsaMRB5LWkXpb0PkpvkAkr0lYHAa9bWsh7h0w0NwZuyJ8VyUQR6j5yML+EnvmUeNSZpzAV0WUdoo2r6tQ9E43C3Xfto+8e0t/0hq90SyFf9Y1rMLjTelN/vUZwIDAQAB
        -----END PUBLIC KEY-----
        """

        alipay = AliPay(
            appid=settings.APPID,
            app_notify_url=None,
            app_private_key_string=app_private_key_string,
            alipay_public_key_string=alipay_public_key_string,
            sign_type=settings.SIGN_TYPE,
            debug=settings.DEBUG
        )
        dict_data = request.GET.dict()
        sign = dict_data.pop('sign')
        trade_no = dict_data.get('trade_no')
        out_trade_no = dict_data.get('out_trade_no')
        print(sign, trade_no, out_trade_no)
        if not all([sign, trade_no, out_trade_no]):
            return http.HttpResponseForbidden('非法请求')

        success = alipay.verify(dict_data, sign)
        if not success:
            return http.HttpResponseForbidden('订单信息被篡改')
        try:
            PayModel.objects.create(
                out_trade_no_id=out_trade_no,
                trade_no=trade_no,
            )
        except Exception as e:
            return render(request, 'pay_success.html', context={'order_id': out_trade_no})

        OrderInfo.objects.filter(order_id=out_trade_no).update(status=OrderInfo.ORDER_STATUS_ENUM['FINISHED'])

        context = {
            'order_id': out_trade_no
        }

        return render(request, 'pay_success.html', context=context)